package com.tos.second.controller;


import com.tos.second.common.Result.Result;
import com.tos.second.dto.CategoryAddDto;
import com.tos.second.entity.Category;
import com.tos.second.service.CategoryService;
import com.tos.second.vo.CategoryListVo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/category")

@Slf4j
public class CategoryController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;
    
    /**
     * 获取分类列表
     * @return
     */
    @GetMapping("/getCategory")
    @Cacheable(cacheNames = "allCategory")
    public Result<List<CategoryListVo>> getCategory(){
        log.info("获取分类列表");
        return Result.success(categoryService.getCategory());
    }


    /**
     * 添加分类
     * @param categoryAddDto
     * @return
     */
    @PostMapping("/addCategory")
    public Result<String> addCategory(@RequestBody CategoryAddDto categoryAddDto){
        log.info("添加分类：{}",categoryAddDto.toString());
        categoryService.addCategory(categoryAddDto);
        deleteRedisCaches();
        return Result.success("添加成功");
    }

    @DeleteMapping("/delete/{id}")
    public Result<String> deleteCategory(@PathVariable Long id){
        log.info("删除分类：{}",id);
        categoryService.deleteCategory(id);
        deleteRedisCaches();
        return Result.success("删除成功");
    }



    @GetMapping("/{id}")
    public Result<Category> getCategoryById(@PathVariable Long id){
        log.info("获取分类详情：{}",id);
        return Result.success(categoryService.getCategoryById(id));
    }


    private void deleteRedisCaches() {
        // 定义需要删除的 Redis 缓存键
        List<String> aKeys = Arrays.asList(
                "newGoodsCache",
                "goodsCache",
                "userGoods",
                "home",
                "category_goods",
                "rec_goods",
                "allCategory"
        );
        for (String key : aKeys) {
            Set<String> keys = redisTemplate.keys(key + ":*");
            if (keys != null && !keys.isEmpty()) {
                redisTemplate.delete(keys);
                log.info("删除key成功");
            }
        }
    }

}